"""doc"""
from django.http import HttpRequest, JsonResponse

from app_common import (
    app_try,
    app_page,
    app_except,
    app_str_check,
    app_uuid,
    json_response_utf8_ok,
)


from . import models, ser, wx_api, wx_pay, access_auth


def common_pay(
    request: HttpRequest,
    total_fee: int,
    pay_for: models.WxUserPaymentRecord.PayFor,
    order_title: str,
    shopping=None,
    score=0,
) -> JsonResponse:
    data, out_trade_no = wx_pay.unifiedorder(
        request=request,
        total_fee=total_fee,
        order_title=order_title,
        call_back_url="/api/wx_user/pay_callback/",
        score=score,
        pay_for=pay_for,
        shopping=shopping,
    )

    payment = data.get("respdata").get("payment")

    if not out_trade_no:
        raise app_except.ValueErr

    if not payment:
        raise app_except.ValueErr

    return json_response_utf8_ok(
        {"code": 0, "payment": payment, "out_trade_no": out_trade_no}
    )


def pay_for_promotion(request: HttpRequest, promotion_uuid: str) -> JsonResponse:
    pay_for = models.WxUserPaymentRecord.PayFor.PROMOTION.value
    order_title = "测试-美发-充值"

    _promotion = (
        models.RechargePromotion.objects.filter(deleted=False)
        .filter(uuid=promotion_uuid)
        .first()
    )
    if not _promotion:
        raise app_except.ObjNotExist(msg=f"promotion_uuid: {promotion_uuid}")

    total_fee = _promotion.actual_payment
    return common_pay(
        request=request,
        pay_for=pay_for,
        total_fee=total_fee,
        score=_promotion.score,
        order_title=order_title,
    )


def pay_for_shopping(request: HttpRequest, shopping_uuid: str) -> JsonResponse:
    pay_for = models.WxUserPaymentRecord.PayFor.SHOPPING.value
    order_title = "测试-美发-购物"
    _shopping = (
        models.StoreShopping.objects.filter(deleted=False)
        .filter(uuid=shopping_uuid)
        .first()
    )
    if not _shopping:
        raise app_except.ObjNotExist(msg=f"shopping: {shopping_uuid}")

    total_fee = _shopping.pay_weixin
    return common_pay(
        request=request,
        pay_for=pay_for,
        total_fee=total_fee,
        order_title=order_title,
        shopping=_shopping,
    )


def get_sum_price(good_car_content_s: list[dict]) -> int:
    _sum = 0
    for obj in good_car_content_s:
        good = obj["good"]
        good_sum_price = good["price"] * obj["pay_count"]
        _sum += good_sum_price
    return _sum
